/**
 * Copyright (c) 2016,http://www.365wuliu.com/  All Rights Reserved.
 */
package com.cargo.base.utils;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;

/**
 * HttpClientUtils:远程连接工具类
 * 
 * @Project Name:cargo
 * @File Name:HttpClientUtils.java
 * @Package Name:com.cargo.utils
 * @Creator:wizard
 * @Date:2016年4月18日上午9:09:02
 */
@SuppressWarnings("deprecation")
public class HttpClientUtils {

	public static Logger log = Logger.getLogger(HttpClientUtils.class);
	public static final int connTimeout = 60000;
	public static final int readTimeout = 60000;
	public static final String charset = "UTF-8";
	private static HttpClient client = null;
	public static final String AUTHORIZATION = null;
	
	static {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(128);
		cm.setDefaultMaxPerRoute(128);
		client = HttpClients.custom().setConnectionManager(cm).build();
	}

	/**
	 * 
	 * post: 发出post请求
	 * 
	 * @param url
	 * @param paramsObj
	 * @return
	 * @throws Exception
	 * @return :String
	 * @Creator:wizard
	 * @Date:2016年4月16日 下午11:37:36
	 */
	@SuppressWarnings("unchecked")
	public static String post(String url, Object paramsObj) throws Exception {
		Map<String, String> params = null;
		if (paramsObj != null) {
			params = JsonUtils.jsonToObject(JsonUtils.toJson(paramsObj), Map.class);
		}
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", AUTHORIZATION);
		return post(url, params, headers, connTimeout, readTimeout);
	}

	/**
	 * 
	 * post:真正的post请求
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 * @throws ConnectTimeoutException
	 * @throws SocketTimeoutException
	 * @throws Exception
	 * @return :String
	 * @Creator:wizard
	 * @Date:2016年4月16日 下午11:27:14
	 */
	private static String post(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,
			Integer readTimeout) throws Exception {

		HttpClient client = null;
		HttpPost post = new HttpPost(url);
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> formParams = new ArrayList<NameValuePair>();
				Set<Entry<String, String>> entrySet = params.entrySet();
				for (Entry<String, String> entry : entrySet) {
					formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
				post.setEntity(entity);
			}

			if (headers != null && !headers.isEmpty()) {
				for (Entry<String, String> entry : headers.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}
			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			post.setConfig(customReqConf.build());
			HttpResponse res = null;
			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				try {
					res = client.execute(post);
				} catch (Exception e) {
					throw e;
				}
			}
			return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
		} finally {
			post.releaseConnection();
			if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
	}

	public static String get(String url) throws Exception {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Authorization", AUTHORIZATION);
		return get(url, headers, charset, connTimeout, readTimeout);
	}

	/**
	 * 真正发送一个 GET 请求
	 * 
	 * @param url
	 * @param charset
	 * @param connTimeout
	 *            建立链接超时时间,毫秒.
	 * @param readTimeout
	 *            响应超时时间,毫秒.
	 * @return
	 * @throws ConnectTimeoutException
	 *             建立链接超时
	 * @throws SocketTimeoutException
	 *             响应超时
	 * @throws Exception
	 */
	private static String get(String url, Map<String, String> headers, String charset, Integer connTimeout,
			Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {
		HttpClient client = null;
		HttpGet get = new HttpGet(url);
		String result = "";
		try {
			if (headers != null && !headers.isEmpty()) {
				for (Entry<String, String> entry : headers.entrySet()) {
					get.addHeader(entry.getKey(), entry.getValue());
				}
			}
			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			get.setConfig(customReqConf.build());

			HttpResponse res = null;

			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(get);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				res = client.execute(get);
			}

			result = IOUtils.toString(res.getEntity().getContent(), charset);
		} finally {
			get.releaseConnection();
			if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
		return result;
	}

	/**
	 * 创建 SSL连接
	 * 
	 * @return
	 * @throws GeneralSecurityException
	 */
	private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}

				@Override
				public void verify(String host, SSLSocket ssl) throws IOException {
				}

				@Override
				public void verify(String host, X509Certificate cert) throws SSLException {
				}

				@Override
				public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
				}

			});

			return HttpClients.custom().setSSLSocketFactory(sslsf).build();

		} catch (GeneralSecurityException e) {
			throw e;
		}
	}

	
	
	
	/**
	 * 
	 * post:百旺专用post请求
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 * @throws ConnectTimeoutException
	 * @throws SocketTimeoutException
	 * @throws Exception
	 * @return :String
	 * @Creator:wizard
	 * @Date:2016年4月16日 下午11:27:14
	 */
	@SuppressWarnings("unchecked")
	public static String post_baiwang(String url, Object paramsObj) throws Exception {
		Map<String, String> params = null;
		if (paramsObj != null) {
			params = JsonUtils.jsonToObject(JsonUtils.toJson(paramsObj), Map.class);
		}
		return post(url, params, null, connTimeout, readTimeout);
	}
	

	/**
	 * 
	 * post:百旺专用真正post请求
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @param connTimeout
	 * @param readTimeout
	 * @return
	 * @throws ConnectTimeoutException
	 * @throws SocketTimeoutException
	 * @throws Exception
	 * @return :String
	 * @Creator:wizard
	 * @Date:2016年4月16日 下午11:27:14
	 */
	@SuppressWarnings("unused")
	private static String post_baiwang_real(String url, String xmlString, Integer connTimeout,
			Integer readTimeout) throws Exception {

		HttpClient client = null;
		HttpPost post = new HttpPost(url);
		try {
			if (xmlString != null && (!xmlString.isEmpty())) {
				StringEntity entity = new StringEntity(xmlString);
				post.setEntity(entity);
				post.setHeader("Content-Type","text/xml;charset=ISO-8859-1");
			}

			// 设置参数
			Builder customReqConf = RequestConfig.custom();
			if (connTimeout != null) {
				customReqConf.setConnectTimeout(connTimeout);
			}
			if (readTimeout != null) {
				customReqConf.setSocketTimeout(readTimeout);
			}
			post.setConfig(customReqConf.build());
			HttpResponse res = null;
			if (url.startsWith("https")) {
				// 执行 Https 请求.
				client = createSSLInsecureClient();
				res = client.execute(post);
			} else {
				// 执行 Http 请求.
				client = HttpClientUtils.client;
				try {
					res = client.execute(post);
				} catch (Exception e) {
					return null;
				}
			}
			return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
		} finally {
			post.releaseConnection();
			if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
				((CloseableHttpClient) client).close();
			}
		}
	}
}
